package cn.bitkit.component.common;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * AOP中spel表达式的值
 */
@Slf4j
public class SpelHandler {

    public static String getString(JoinPoint joinPoint, String spel){
        return getValue(joinPoint, spel, String.class);
    }

    public static Boolean getBoolean(JoinPoint joinPoint, String spel){
        return getValue(joinPoint, spel, Boolean.class);
    }

    @SneakyThrows
    public static <T> T getValue(JoinPoint joinPoint, String spel, Class<T> clazz){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Object[] args = joinPoint.getArgs();
        String[] parameterNames = signature.getParameterNames();
        StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
        for (int i = 0; i < args.length; i ++) {
            evaluationContext.setVariable(parameterNames[i], args[i]);
        }
        ExpressionParser expressionParser = new SpelExpressionParser();
        TemplateParserContext parserContext = new TemplateParserContext("{", "}");
        Expression expression = expressionParser.parseExpression(spel, parserContext);
        return expression.getValue(evaluationContext, clazz);
    }

}
